#!/usr/bin/python
import os
import sys
import MySQLdb
import string
import time
import cloud
import pp
import db

def isDigtal(Num):
    nums = string.digits
    myNum = str(Num)
    if type(myNum) is not str:
        return False
    else:
        for temp in myNum:
            if temp not in nums:
                return False
        return True

def checkDeletePara(conn,env_id):
    try:  
        if not conn:
            #print "Can not connect to database, Fail!"
            return -1
        if not isDigtal(env_id):
            return -2
        flag,rows = db.exeFetchCommand(conn,"select env_id from mpi_env where status = 'running' and env_id = " + str(env_id));
        if flag == 0:
            #print "No Job ", env_id
            return -2
        return 1
    except: 
        #exception
        return -5

def delJobs(env_id):
    #try:  
        connect=db.connectDB()
        conn=db.cursorDB(connect)
        flag = checkDeletePara(conn,env_id)
        # flag = -1: database connection fail.
        # flag = -2: Parameter error. 
        # flag = -5: exception
        if flag < 0:
            db.closeCursor(conn)
            db.closeConnect(connect)
            return flag
        tmp = str(time.time()).split('.')
        thistime=tmp[0]
        db.exeSetCommand(conn,"update mpi_env set status = 'finish' where env_id="+str(env_id))
        db.exeSetCommand(conn,"update mpi_env set end_time = " + thistime + " where env_id = " + str(env_id))
        cnt,rows = db.exeFetchCommand(conn,"select vm_uid from env_resource where env_id="+str(env_id)) 
        db.closeCursor(conn)
        db.closeConnect(connect)
	
        for tmp in rows:
            	print tmp[0]
		cloud.del_vm(tmp[0])
        #print "Job "+str(env_id)+" is deleted!"
        #Delete successful, return job_id
        return env_id
    #except: 
        #exception
        return -5

